package com.bytedance.lucky.aspect;

import com.bytedance.lucky.http.RequestHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @author zouyaowen
 * @date 2021-02-12 21:09
 */
@RestControllerAdvice(annotations = {RestController.class})
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object object, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 统一返回值类型处理
        CommonResponse response = null;
        if (null == object) {
            response = CommonResponse.success();
        } else if (object instanceof CommonResponse) {
            response = (CommonResponse) object;
        } else {
            CommonResponse<Object> res = CommonResponse.success();
            res.setData(object);
            response = res;
        }
        response.setRt(LocalDateTime.now());
        Optional<RequestHolder.RequestInfo> requestInfoP = RequestHolder.getRequestInfo();
        if (requestInfoP.isPresent()) {
            response.setQt(requestInfoP.get().getQt());
        }
        return response;
    }
}
